﻿// -----------------------------------------------------------------------
// <copyright file="PSCachingAdminDataRepository.NamedCache.cs" company="Matthieu Klotz">
// Copyright (c) 2012, Matthieu Klotz
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// - Neither the name of Matthieu Klotz nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// </copyright>
// -----------------------------------------------------------------------

namespace AppFabric.Admin.Service.DataAccess
{
    using System.Collections.Generic;
    using System.Management.Automation;
    using AppFabric.Admin.Service.DataAccess.Datas;
    using AppFabric.Admin.Service.DataAccess.Helpers;
    using Microsoft.ApplicationServer.Caching.AdminApi;
    using Microsoft.ApplicationServer.Caching.Commands;

    /// <summary>
    /// Contains functionalities for administrate named caches.
    /// </summary>
    public sealed partial class PSCachingAdminDataRepository
    {
        /// <inheritdoc />
        public IList<NamedCache> GetCache(string hostName, int portNo = 22233)
        {
            Dictionary<string, object> parameters = null;
            if (!string.IsNullOrWhiteSpace(hostName))
            {
                parameters = new Dictionary<string, object>
                {
                    { PSAdminParamsConstants.HostName, hostName },
                    { PSAdminParamsConstants.PortNo, portNo }
                };
            }

            IList<PSObject> results = this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.GetCache, parameters);
            List<NamedCache> namedCaches = null;
            if (results != null && results.Count > 0)
            {
                namedCaches = new List<NamedCache>(results.Count);
                foreach (PSObject psobject in results)
                {
                    if (psobject != null)
                    {
                        CacheInfo cacheInfo = psobject.BaseObject as CacheInfo;
                        if (cacheInfo != null)
                        {
                            NamedCache namedCache = new NamedCache
                            {
                                CacheName = cacheInfo.CacheName,
                                HostRegionMap = cacheInfo.HostRegionMap
                            };

                            namedCaches.Add(namedCache);
                        }
                    }
                }
            }

            return namedCaches;
        }

        /// <inheritdoc />
        public void NewCache(CacheConfiguration cacheConfiguration)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { PSAdminParamsConstants.CacheName, cacheConfiguration.CacheName },
                { PSAdminParamsConstants.Eviction, cacheConfiguration.EvictionType.ToString() },
                { PSAdminParamsConstants.Expirable, cacheConfiguration.IsExpirable },
                { PSAdminParamsConstants.NotificationsEnabled, cacheConfiguration.NotificationsEnabled },
                { PSAdminParamsConstants.TimeToLive, cacheConfiguration.TimeToLive },
                { PSAdminParamsConstants.Secondaries, cacheConfiguration.Secondaries },
                { PSAdminParamsConstants.ForceCommand, null }
            };

            this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.NewCache, parameters);
        }

        /// <inheritdoc />
        public void RemoveCache(string cacheName)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { PSAdminParamsConstants.CacheName, cacheName }
            };

            this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.RemoveCache, parameters);
        }

        /// <inheritdoc />
        public CacheConfiguration GetCacheConfig(string cacheName)
        {
            CacheConfiguration configuration = null;
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { PSAdminParamsConstants.CacheName, cacheName }
            };

            IList<PSObject> results = this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.GetCacheConfig, parameters);
            if (results != null && results.Count > 0)
            {
                PSObject result = results[0];
                if (result != null)
                {
                    CacheConfig cacheConfig = result.BaseObject as CacheConfig;
                    if (cacheConfig != null)
                    {
                        configuration = cacheConfig.ToCacheConfiguration();
                    }
                }
            }

            return configuration;
        }

        /// <inheritdoc />
        public void SetCacheConfig(CacheConfiguration cacheConfiguration)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                { PSAdminParamsConstants.CacheName, cacheConfiguration.CacheName },
                { PSAdminParamsConstants.Eviction, cacheConfiguration.EvictionType },
                { PSAdminParamsConstants.Expirable, cacheConfiguration.IsExpirable },
                { PSAdminParamsConstants.NotificationsEnabled, cacheConfiguration.NotificationsEnabled },
                { PSAdminParamsConstants.TimeToLive, cacheConfiguration.TimeToLive },
                { PSAdminParamsConstants.Secondaries, cacheConfiguration.Secondaries },
                { PSAdminParamsConstants.ForceCommand, null }
            };

            this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.SetCacheConfig, parameters);
        }

        /// <inheritdoc />
        public IList<Region> GetCacheRegions(string cacheName)
        {
            Dictionary<string, object> parameters = new Dictionary<string, object>
            {
                 { PSAdminParamsConstants.CacheName, cacheName }
            };

            IList<Region> regions = null;
            IList<PSObject> result = this.powerShellRunSpace.InvokeCommand(PSAdminCommandsConstants.GetCacheRegion, parameters);
            if (result != null && result.Count > 0)
            {
                regions = new List<Region>(result.Count);
                foreach (PSObject powerShellObject in result)
                {
                    if (powerShellObject == null)
                    {
                        continue;
                    }

                    RegionInfo regionInfo = powerShellObject.BaseObject as RegionInfo;
                    if (regionInfo != null)
                    {
                        Region region = regionInfo.ToDataRegion();
                        if (region != null)
                        {
                            regions.Add(region);
                        }
                    }
                }
            }

            return regions;
        }
    }
}
